package com.shm.leetcode.concurrent;

import java.util.function.IntConsumer;

class FizzBuzz1 {
    private int n;

    public FizzBuzz1(int n) {
        this.n = n;
    }

    volatile int f = 0;

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        for (int i = 3; i <= n; i += 3) {
            if (i % 5 != 0) {
                while (f != 3) {
                    Thread.yield();
                }

                printFizz.run();
                f = 0;
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        for (int i = 5; i <= n; i += 5) {
            if (i % 3 != 0) {
                while (f != 2) {
                    Thread.yield();
                }
                printBuzz.run();
                f = 0;
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        for (int i = 15; i <= n; i += 15) {
            while (f != 1) {
                Thread.yield();
            }
            printFizzBuzz.run();
            f = 0;
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            while (f != 0) {
                Thread.yield();
            }
            if (i % 15 == 0) {
                f = 1;
            } else if (i % 5 == 0) {
                f = 2;
            } else if (i % 3 == 0) {
                f = 3;
            } else {
                printNumber.accept(i);
            }
        }
    }
}